package com.wits.qso.web.controller;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wits.platform.common.constants.WebConstants;
import com.wits.platform.web.controller.BaseController;
import com.wits.qso.entity.Btable;
import com.wits.qso.entity.Cls;
import com.wits.qso.entity.Teacher;
import com.wits.qso.entity.Year;
import com.wits.qso.service.BtableDaoService;
import com.wits.qso.service.ClsService;
import com.wits.qso.service.CourseService;
import com.wits.qso.service.DeptService;
import com.wits.qso.service.GradeService;
import com.wits.qso.service.TeacherService;
import com.wits.qso.service.YearService;

/**
 *代课设定
 */
@Controller
@RequestMapping(value = "qso/subcourse")
public class SubCourseController extends BaseController {
	
	@Autowired
	private YearService yearService;
	@Autowired
	private BtableDaoService btableDaoService;
	@Autowired
	private TeacherService teacherService;
	@Autowired
	private ClsService clsService;
	@Autowired
	private CourseService courseService;
	@Autowired
	private DeptService deptService;
	@Autowired
	private GradeService gradeService;
	
	@RequestMapping(value = "/toList")
	public String toList(Model model) {
		model.addAttribute( "teachers", teacherService.findAll() );
		model.addAttribute( "currentUserId", getCurrentUserId() );
		model.addAttribute( "currentWeek", getCurrentWeeksOfYear() );
		model.addAttribute( "totalWeeks", getWeeksOfThisYear() );
		model.addAttribute( "eventDataJson", btableDaoService.getEventsJson( teacherService.findByUserId( getCurrentUser().getId() ) ) );
		return "qso/subcourse/list";
	}
	
	@RequestMapping(value="/listjson")
	@ResponseBody
	public String toListJson(Model model,@RequestParam String terid){
		return btableDaoService.getEventsJson( teacherService.getOne(terid));
	}
	
	/**
	 * 新增
	 * @param model
	 * @param id 基本课表编号
	 * @return
	 */
	@RequestMapping(value="view/{viewType}")
	public String toAdd(Model model,@PathVariable String viewType,@RequestParam String id){
		Btable bt=btableDaoService.getOne(id);
		List<Btable> btList=btableDaoService.findByWedayAndClass(bt.getWeday(), bt.getCalss(),bt.getCrmid());
		
		List<Teacher> teaList= teacherService.findAll();
		List<Cls> clsList=clsService.findAll();
		
		if(bt.getTeaid()==null && bt.getClaid()==null)
		if(btList!=null && btList.size()>0){
			for(int i=0;i<btList.size();i++){
				Btable ta=btList.get(i);
				if(ta.getTeaid()!=null){
					if(teaList.indexOf(ta.getTeaid())>-1)
						teaList.remove(teaList.indexOf(ta.getTeaid()));
				}	
				if(ta.getClaid()!=null){
					if(clsList.indexOf(ta.getClaid())>-1)
					clsList.remove(clsList.indexOf(ta.getClaid()));
				}
			}
		}
		model.addAttribute("teachers",teaList);
		model.addAttribute("id",id);
		model.addAttribute(WebConstants.COMMAND,bt);
		model.addAttribute("viewType", viewType);
		return "qso/subcourse/form";
	}
	
	@RequestMapping(value="/save",method=RequestMethod.POST)
	@ResponseBody
	public Object save(Model model,
			@ModelAttribute("command") @Valid Btable command,@RequestParam String terid,
			@RequestParam String viewType,
			BindingResult result,
			HttpServletRequest req){
		if(result.hasErrors()){
			model.addAttribute(WebConstants.COMMAND, command);
			return toAdd(model, viewType, command.getId());
		}
		
		command.setDateUpd(new Date());
		command.setUserUpd(getCurrentUserId());
		try {
			command.setTeaid(teacherService.getOne(terid));
			btableDaoService.save(command);
			
			return ajaxDoneSuccess(this.getText("save.success"));
		} catch (Exception e) {
			return ajaxDoneError(this.getText("save.failed"), e);
		}
	}
	
	protected int getCurrentWeeksOfYear() {
		int weeks = 1;
		Year year = yearService.findEnabled();

		if (null != year) {
			Calendar current = Calendar.getInstance();
			current.set( Calendar.HOUR_OF_DAY, 0 );
			current.set( Calendar.MINUTE, 0 );
			current.set( Calendar.SECOND, 0 );
			current.set( Calendar.MILLISECOND, 0 );

			Calendar start = Calendar.getInstance();
			start.setTime( year.getDateF() );

			long diff = current.getTimeInMillis() - start.getTimeInMillis();
			int dayCount = new Float( (float) diff / (24 * 60 * 60 * 1000) ).intValue();

			weeks = dayCount / 7 + (0 != (dayCount % 7) ? 1 : 0);
		}

		return weeks;
	}

	protected int getWeeksOfThisYear() {
		Year year = yearService.findEnabled();
		int weeks = 1;

		if (null != year) {
			Calendar start = Calendar.getInstance();
			Calendar end = Calendar.getInstance();
			start.clear();
			end.clear();

			start.setTime( year.getDateF() );
			end.setTime( year.getDateT() );

			long diff = end.getTimeInMillis() - start.getTimeInMillis();

			int dayCount = new Float( (float) diff / (24 * 60 * 60 * 1000) ).intValue();

			weeks = dayCount / 7 + (0 != (dayCount % 7) ? 1 : 0);
		}

		return weeks;
	}
}
